import { type Option } from '../../../../../types';
import { IBaseSelector } from '../../../selector/base';

abstract class ApprovalService<T extends Option> extends IBaseSelector {
  abstract options: T[];
  value: Array<string | T> = [];
  abstract prefix: string;

  onChange(value: T[]) {
    this.value = value;
    // 注入会签、或签逻辑
    this.onChangeCallback?.(value);
    // 会签、或签在用户前面更新，否则导致assignee被清空
    this.updateProperties(value);
  }

  onChangeCallback?: (val: T[]) => void;

  bindOnChange(onChange?: (val: T[]) => void) {
    this.onChangeCallback = onChange;
  }

  updateProperties(value: T[]) {
    const element = this.panel.getElement();
    this.root.getModeling().updateProperties(
      element,
      {
        'flowable:assignee': undefined, // 多选时，清空单选
        'flowable:candidateGroups': value.map(it => this.prefix + it.value).join(','),
        'flowable:text': value.map(it => it.label).join(',')
      },
    );
  }

  init() {
    const element = this.panel.getElement();
    const ids = element.businessObject.candidateGroups as string || '';
    if (ids) {
      const rawIdArr = ids.split(',');
      const idArr = rawIdArr.map(it => it.replace(new RegExp('^' + this.prefix), ''));
      const labels = element.businessObject.$attrs['flowable:text'] as string || '';
      const labelArr = labels.split(',');
      this.value = idArr.map((it, index) => ({ value: it, label: labelArr[index] })) as T[];
    } else {
      this.value = [];
    }

    // console.log('this.value', this.value,element.businessObject.$attrs,this.value,element.businessObject);
  }

}

export default ApprovalService;
